<?php
namespace app\admin\service;

class Rule
{
    protected $rules;
    function __construct($rules)
    {
        $this->rules = $rules;
    }
    function check($path)
    {
        $path_arr = explode('/',preg_replace(['/^\//','/\.[^\/]+$/'],'',$path));
        $bool = false;
        foreach($this->rules as $key=>$rule){
            if(!isset($path_arr[$key])){
                return false;
            }
            $bool = $this->checkItem($rule,$path_arr[$key]);
            if($bool === 'all'){
                return true;
            }
            if(!$bool){
                return false;
            }

        }
        if($key == count($path_arr) - 1){
            return true;
        }
        return false;
    }

    function checkItem($rule,$token)
    {
        switch($rule['type']){
            case '**':
                return 'all';
                break;
            case '*':
                return true;
                break;
            case '$':
                if(preg_match('/^[0-9]+$/',$token)){
                    return true;
                }
                break;
            case 'enum':
                foreach($rule['value'] as $enum){
                    if($enum == $token){
                        return true;
                    }
                }
                break;
            case 'between':
                if(!preg_match('/^[0-9]+$/',$token)){
                    return false;
                }
                $token = (int)$token;
                if($token >= $rule['value'][0] && $token <= $rule['value'][1] ){
                    return true;
                }
                break;
            case 'const':
                if($token == $rule['value']){
                    return true;
                }
        }
        return false;
    }
}